/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.answer.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.ruoyi.blog.controller;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.util.StrUtil;
import com.anji.captcha.model.common.ResponseModel;
import com.anji.captcha.service.CaptchaService;
import com.ruoyi.blog.common.annotation.Login;
import com.ruoyi.blog.form.CaptchaForm;
import com.ruoyi.blog.form.UserForm;
import com.ruoyi.common.utils.JwtUtil;
import com.ruoyi.common.utils.R;
import com.ruoyi.easywenku.entity.User;
import com.ruoyi.easywenku.service.UserService;
import com.ruoyi.third.sms.SmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 注册接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/api")
@Api(tags = "用户接口")
@AllArgsConstructor
public class ApiUserController {

    final public UserService userService;
    private CaptchaService captchaService;
    private static Cache<String,String> captchaCache= CacheUtil.newLRUCache(1000,1000*60*15);
    @PostMapping("register")
    @ApiOperation("注册")
    public R register(@Validated @RequestBody UserForm user) {
        user.setCreateTime(new Date());
        user.setStatus("1");

        if (StrUtil.isBlank(user.getPhoneVerificationCode())|| !user.getPhoneVerificationCode().equals(captchaCache.get(user.getPhone()))) {
            return R.failed("手机验证码错误");
        }

        if (StrUtil.isAllBlank(user.getEmail(), user.getPhone(), user.getPassword())) {
            return R.failed("必填字段为空");
        }
        //.eq(StrUtil.isNotBlank(user.getEmail()), User::getEmail, user.getEmail())
        //                .or(
        User one = userService.lambdaQuery().eq(StrUtil.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .one();
        if (one != null) {
            StringBuilder info = new StringBuilder();
            if (one.getPhone() != null && one.getPhone().equals(user.getPhone())) {
                info.append("手机号,");
            }
            if (one.getEmail() != null && one.getEmail().equals(user.getEmail())) {
                info.append("邮箱,");
            }
            info.append("已经注册");
            return R.failed(info.toString());
        }
        userService.save(user);
        return R.ok(null,"注册成功");

    }
    @PostMapping("forgetPassword")
    @ApiOperation("注册")
    public R forgetPassword(@Validated @RequestBody UserForm user) {

        if (StrUtil.isBlank(user.getPhoneVerificationCode())|| !user.getPhoneVerificationCode().equals(captchaCache.get(user.getPhone()))) {
            return R.failed("手机验证码错误");
        }

        if (StrUtil.isAllBlank( user.getPhone(), user.getPassword())) {
            return R.failed("必填字段为空");
        }

        User one = userService.lambdaQuery().eq(StrUtil.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .one();
        if (one == null) {
            return R.failed("用户不存在");
        }
        one.setPassword(user.getPassword());
        userService.updateById(one);
        return R.ok(null,"修改成功");
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public R login(@RequestBody User user, HttpServletResponse response) {
        User one = userService.lambdaQuery()
                .eq(StrUtil.isNotBlank(user.getAccount()), User::getAccount, user.getAccount()).or()
                .eq(StrUtil.isNotBlank(user.getEmail()), User::getEmail, user.getEmail()).or()
                .eq(StrUtil.isNotBlank(user.getPhone()), User::getPhone, user.getPhone())
                .eq(User::getPassword, user.getPassword())
                .eq(User::getStatus, "1")
                .one();
        if (one != null) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("token", JwtUtil.sign(one.getUserId().toString()));
            return R.ok(hashMap, "登录成功");
        }
        return R.failed("用户名不存在或密码错误");
    }

    @GetMapping("userInfo")
    @ApiOperation("用户信息")
    @Login
    public R<User> userInfo(@RequestAttribute("userId") Long userId) {
        User one = userService.getById(userId);
        if (one != null) {
            return R.ok(one);
        }
        return R.failed();
    }

    @PostMapping("getCaptcha")
    @ApiOperation("获取验证码")
    public R<String> getCaptcha(@RequestBody CaptchaForm captchaForm) {


       // ResponseModel response = captchaService.verification(captchaForm);
       // if(!response.isSuccess()){
       //     return R.failed(response.getRepMsg());
       // }

        Random ran = new Random();
        int num = ran.nextInt(999999);

        String captcha = String.format("%06d", num);
        captchaCache.put(captchaForm.getPhone(),captcha);
        if (phoneBool(captchaForm.getPhone()) && SmsUtil.sendAliRegisterSms(captchaForm.getPhone(), captcha)) {
            return R.ok("发送成功","发送成功");
        } else {
            return R.failed("手机号不正确！");
        }

    }

    //手机号验证
    public boolean phoneBool(String phone) {
        if (phone == null || phone.isEmpty()){
            return false;
        }
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }


}
